package com.hht.myapplication;

import android.Manifest;
import android.text.ClipboardManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * 语音小助手
 * hht
 */
public class MainActivity extends AppCompatActivity {
    //接收转换的文字流
    DataInputStream dis;
    //音频流上传通道
    OutputStream ous;

    String serverIp = "101.201.XX.XX";
    int serverPort = 5555;

    private TextView realText;
    private TextView finalText;

    //音频相关
    AudioRecord audioRecord=null;
    int bufferSize=0;//最小缓冲区大小
    int sampleRateInHz = 16000;//采样率
    int channelConfig = AudioFormat.CHANNEL_IN_DEFAULT; //单声道
    int audioFormat = AudioFormat.ENCODING_PCM_16BIT; //量化位数
    private boolean isRecording = true;
    private Handler handler=null;


    private  String content ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        realText = (TextView) findViewById(R.id.textView2);
        finalText = (TextView) findViewById(R.id.textView);
        finalText.setMovementMethod(ScrollingMovementMethod.getInstance()) ;
        handler = new Handler();

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE)  != PackageManager.PERMISSION_GRANTED)  {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO},1);
        } else {
            init();
        }
    }

    public void onClickCopy(View v) {
        // 从API11开始android推荐使用android.content.ClipboardManager
        // 为了兼容低版本我们这里使用旧版的android.text.ClipboardManager，虽然提示deprecated，但不影响使用。
        ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        // 将文本内容放到系统剪贴板里。
        cm.setText(finalText.getText());
        Toast.makeText(this, "复制成功，可以发给朋友们了。", Toast.LENGTH_LONG).show();
    }


    public void init(){
        System.out.println("初始化录音");
        bufferSize = AudioRecord.getMinBufferSize(sampleRateInHz,channelConfig, audioFormat)+1000;//计算最小缓冲区
        try{
            audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC,sampleRateInHz,channelConfig, audioFormat, bufferSize);//创建AudioRecorder对象

            Runnable startRunnable = new Runnable(){
                @Override
                public void run() {
                    connect();
                    new sendDataThread().start();
                    new getDataThread().start();
                }
            };
            new Thread(startRunnable).start();
        }catch (Exception e){
            e.printStackTrace();
        }

        System.out.println("初始化录音成功");
    }


    public void connect(){
        try{
            Socket socket = new Socket(serverIp,serverPort);
            InputStream is=socket.getInputStream();
            ous = socket.getOutputStream();
            dis=new DataInputStream(is);
        }catch(IOException e){
            e.printStackTrace();
        }
    }




    //发送数据
    class sendDataThread extends Thread {
        public void run() {
            byte[] buffer = new byte[bufferSize];
            audioRecord.startRecording();//开始录音
            int r = 0;

            try {
                while (isRecording&&audioRecord.read(buffer,0,bufferSize)>0) {
                    ous.write(buffer);
                    ous.flush();
                }
                audioRecord.stop();//停止录音
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    //接收数据
    class getDataThread extends Thread {
        public void run() {
            while (true) {
                String msg;
                try {
                    msg = dis.readUTF();
                    if (!"status".equals(msg)&&!"".equals(msg)) {//status 为心跳检测
                        content=msg;
                        handler.post(runnableUi);

                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

    // 构建Runnable对象，在runnable中更新界面
    Runnable   runnableUi=new  Runnable(){
        @Override
        public void run() {
            //更新界面
            realText.setText(content);
            finalText.append(content);
            //跳转到底部
            int offset=finalText.getLineCount()*finalText.getLineHeight();
            if(finalText.getLineCount()>15 && offset>finalText.getHeight()){
                finalText.scrollTo(0,offset-finalText.getHeight());
            }
        }
    };

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case 1: {
                if (grantResults.length > 0  && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 权限被用户同意，可以去放肆了。
                    init();
                } else {
                    // 权限被用户拒绝了，洗洗睡吧。
                }
                return;
            }
        }
    }
}